<?php

namespace App\Http\Controllers;

use App\Models\Floor;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class FloorController extends Controller
{
    /**
     * @return void
     */
    public function floorList(Request $request)
    {
        $validatedData = $request->validate([
            'page' => 'nullable|integer',
            'pageSize' => 'nullable|integer',
        ]);
        $pageSize = $validatedData['pageSize'] ?? 20; // 默认每页20条记录
        $users = Floor::paginate($pageSize);
        $data = [
            'page' => $users->currentPage(),
            'pageSize' => intval($users->perPage()),
            'rows' => $users->items(),
            'total' => $users->total(),
        ];
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data
        ];
        return Response()->json($responseJson);
    }

    /**
     * @return void
     */
    public function floorAdd(Request $request)
    {
        $val = $request->validate(
            [
                "id" => 'nullable',
                'name' => 'required'
            ]
        );
        if (!empty($val['id'])) {
            $data = Floor::find($val['id']);
            $data->name = $val['name'];
            $data->save();
        } else {
            $data = Floor::create($val);
        }
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data->id
        ];
        return Response()->json($responseJson);
    }

    /**
     * @param Request $request 楼层图片上传
     * @return \Illuminate\Http\JsonResponse
     */
    public function addImage(Request $request)
    {
        $val = $request->validate([
            'file' => 'required|file|mimes:jpg,png,jpeg,gif,bmp|max:20480', // 最大允许上传XXKB
            'floor_id' => 'required'
        ]);
        $data = Floor::find($val['floor_id']);
        $path = $request->file('file')->store('floor_pic'); // 相对路径
        $data->pic= $path;
        $data->save();
        $data = [
            'code' => 200,
            'message' => '',
            'data' => [
                'src' => Storage::url($path),
            ]
        ];
        $responseJson = [
            'code' => 200,
            'message' => '',
            'data' => $data,
        ];
        return Response()->json($responseJson);
    }

    /**
     * @return void
     */
    public function floorDel($ids)
    {
        if (strpos($ids, ',') !== false) {
            $numbers = explode(',', $ids);
            foreach ($numbers as $num) {
                $menu = Floor::findOrFail($num);
                $menu->delete();
            }
        } else {
            $menu = Floor::findOrFail($ids);
            $menu->delete();
        }
        $responseJson = [
            'code' => 200,
            'message' => '成功删除',
        ];
        return response()->json($responseJson);
    }
}
